package com.maokeyang.messageboard.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.maokeyang.messageboard.dto.MessageDto;
import com.maokeyang.messageboard.mapper.MessageMapper;
import com.maokeyang.messageboard.mapper.UserMapper;
import com.maokeyang.messageboard.model.Message;
import com.maokeyang.messageboard.model.User;
import com.maokeyang.messageboard.service.MessageService;
import com.maokeyang.messageboard.util.PageRequest;
import com.maokeyang.messageboard.util.PageResult;
import com.maokeyang.messageboard.util.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 获取留言列表
     *
     * @param pageRequest
     * @return
     */
    @Override
    public Map<String, Object> getMessageList(PageRequest pageRequest) {
        Map<String, Object> attributes = new HashMap<>();
        PageResult pageResult = PageUtils.getPageResult(pageRequest, getPageInfo(pageRequest));
        attributes.put("messages", pageResult);
        attributes.put("messageDto", new MessageDto());
        return attributes;
    }

    /**
     * 调用分页插件完成分页
     * @param pageRequest
     * @return
     */
    private PageInfo<Message> getPageInfo(PageRequest pageRequest) {
        int pageNum = pageRequest.getPageNum();
        int pageSize = pageRequest.getPageSize();
        PageHelper.startPage(pageNum, pageSize);
        List<Message> messages = messageMapper.selectPage();
        return new PageInfo<Message>(messages);
    }

    /**
     * 更新留言
     * @param message
     */
    @Override
    @Transactional
    public void updateMessage(Message message) {
        messageMapper.updateByPrimaryKeySelective(message);
    }

    /**
     * 添加留言
     *
     * @param message
     */
    @Override
    @Transactional
    public void addMessage(Message message) {
        messageMapper.insert(message);
        userMapper.incrMsgCount(message.getUid());
    }

    /**
     * 删除留言
     *
     * @param id
     */
    @Override
    @Transactional
    public void delMessage(Integer id) {
        Message message = messageMapper.selectByPrimaryKey(id);
        messageMapper.deleteByPrimaryKey(id);
        userMapper.decrMsgCount(message.getUid());
    }
}
